using System;
using System.Linq;
using OFX.Aggregator.Infrastructure;

namespace OFX.Aggregator.Implementation
{
	public sealed class StatementInterpreterHelper
	{
		public static void InferStatementDates(Statement statement)
		{
			if (statement.PaymentOriginators.Count > 0)
			{
				foreach (PaymentOriginator paymentOriginator in statement.PaymentOriginators)
				{
					if (paymentOriginator.StatementLines.Count > 0)
					{
						DateTime firstLineDate =
							(from statementLine in paymentOriginator.StatementLines select statementLine.DatePosted).Min();
						DateTime lastLineDate =
							(from statementLine in paymentOriginator.StatementLines select statementLine.DatePosted).Max();

						if (statement.DateStart == DateTime.MinValue || firstLineDate < statement.DateStart)
							statement.DateStart = firstLineDate;
						if (statement.DateEnd == DateTime.MinValue || lastLineDate < statement.DateEnd)
							statement.DateEnd = lastLineDate;
					}
				}
			}
		}
	}
}